﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using WAF.EntityFramework;
using WfhTrader.Core.Entity;

namespace WfhTrader.Core.Trading
{
    /// <summary>
    /// 账户管理类
    /// </summary>
    public class AccountManager
    {
        /// <summary>
        /// 单例模式实例对象
        /// </summary>
        private static AccountManager instance;

        /// <summary>
        /// 所有CTP账户列表
        /// </summary>
        private List<CtpAccount> ctpAccounts;



        /// <summary>
        /// 取得账户管理类对象实例
        /// </summary>
        /// <returns>账户对象实例</returns>
        public static AccountManager GetInstance()
        {
            if (instance == null)
                instance = new AccountManager();

            return instance;
        }

        /// <summary>
        /// 所有CTP账户
        /// </summary>
        /// <returns>所有CTP账户列表</returns>
        public List<CtpAccount> CtpAccounts
        {
            get
            {
                if (this.ctpAccounts == null)
                {
                    this.ctpAccounts = new List<CtpAccount>();

                    EntitySession dbo = new EntitySession();
                    dbo.BeginTransaction();

                    try
                    {
                        WfhTrader.Core.Entity.CtpAccount[] accounts = dbo.Select<WfhTrader.Core.Entity.CtpAccount>("SELECT * FROM CtpAccount");

                        foreach (WfhTrader.Core.Entity.CtpAccount account in accounts)
                        {
                            WfhTrader.Core.Entity.CtpBroker broker = dbo.Select<WfhTrader.Core.Entity.CtpBroker>(account.BrokerID);

                            CtpBroker ctpBroker = new CtpBroker(broker.BrokerCode, broker.BrokerName);
                            CtpAccount ctpAccount = new CtpAccount(ctpBroker, (PurposeType)account.Purpose, account.AccountNumber, account.Password, account.Remark);

                            this.ctpAccounts.Add(ctpAccount);
                        }
                    }
                    finally
                    {
                        dbo.CommitTtransaction();
                    }
                }

                return this.ctpAccounts;
            }
        }

        /// <summary>
        /// 获取指定账号的账户
        /// </summary>
        /// <param name="accountNumber">账号</param>
        /// <returns>账户</returns>
        public CtpAccount GetCtpAccount(string accountNumber)
        {
            CtpAccount ctpAccount = null;

            foreach (CtpAccount account in this.CtpAccounts)
            {
                if (account.AccountNumber == accountNumber)
                {
                    ctpAccount = account;
                    break;
                }
            }

            return ctpAccount;
        }
    }
}
